package com.nsgf.library.ui.page.video;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.databinding.ActivityNsgfHomeVideoDetailsBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.skjz.utils.StringUtil;
import com.nsgf.skjz.utils.ToastUtils;

public class VideoInfoActivity extends BaseActivity {

    StateHolder mStates;

    AccountRequester mAccountRequester;

    private boolean mIsListened = false;
    private int m_iPreviewHandle = -1;

    private ActivityNsgfHomeVideoDetailsBinding mBinding;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_nsgf_home_video_details, BR.vm, mStates);
    }

    private boolean isLandscape = false;
    private String token;
    private String rtmpUrl;
    private int channelNo;

    private String lat = "", lon = "";

    String easyPlayer = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);

        mBinding = (ActivityNsgfHomeVideoDetailsBinding) getBinding();
        mStates.titleBar.set(getIntent().getStringExtra("deviceName"));
        mBinding.titlebar.titleBarClear.setVisibility(View.VISIBLE);
        mBinding.titlebar.titleBarClear.setImageResource(R.drawable.ic_nsgf_video_big);
        mBinding.titlebar.titleBarClear.setOnClickListener(view -> {
            if (isLandscape) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mBinding.titlebar.titleBarRoot.setBackgroundColor(getResources().getColor(R.color.white));
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mBinding.titlebar.titleBarRoot.setBackgroundColor(getResources().getColor(R.color.transparent));
            }
            isLandscape = !isLandscape;

        });
        lat = getIntent().getStringExtra("lat");
        lon = getIntent().getStringExtra("lon");

        // 暂无法播放视频
        WebSettings mWebEasyPlayerSettings = mBinding.webViewEasyPlayer.getWebView().getSettings();
        mWebEasyPlayerSettings.setJavaScriptEnabled(true);//设置支持javaScript

        // 支持 WebSocket 和混合内容
        mWebEasyPlayerSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        mWebEasyPlayerSettings.setAllowFileAccess(true);
        mWebEasyPlayerSettings.setAllowContentAccess(true);
        mWebEasyPlayerSettings.setAllowFileAccessFromFileURLs(true);
        mWebEasyPlayerSettings.setAllowUniversalAccessFromFileURLs(true);
        mWebEasyPlayerSettings.setDomStorageEnabled(true); // 启用 DOM 存储，支持 WebSocket
        mWebEasyPlayerSettings.setDatabaseEnabled(true); // 启用数据库
        mWebEasyPlayerSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); // 不使用缓存

        //正式打包
        easyPlayer = APIs.HTTP_H5.replace("#", "/easyPlayer.html?url=");


        String url = "file:///android_asset/roadLine/index.html";
        WebSettings mWebSettings = mBinding.webView.getWebView().getSettings();
        mWebSettings.setJavaScriptEnabled(true);//设置支持javaScript
        mBinding.webView.loadUrl(url);
        // 当页面加载完成后调用JavaScript方法
        mBinding.webView.getWebView().setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                JsonObject jsonObject = new JsonObject();
                jsonObject.addProperty("lat", lat);
                jsonObject.addProperty("lon", lon);
                jsonObject.addProperty("status", 5);
                callJavaScriptZoomToPointFunction(jsonObject);

            }
        });

        mStates.channelId.set(getIntent().getStringExtra("channelId"));
        mStates.deviceCode.set(getIntent().getStringExtra("deviceCode"));
        mStates.callingMode.set(getIntent().getStringExtra("callingMode"));

        mAccountRequester.videoInfo(mStates.deviceCode.get(), mStates.channelId.get(), mStates.callingMode.get());
        mAccountRequester.getVideoSrc().observe(this, responseStatusDataResult -> {

            if (null == responseStatusDataResult.getResult()) {
                ToastUtils.showLongToast(responseStatusDataResult.getMsg());
                return;
            }
            if (null != responseStatusDataResult.getResult().getData()) {

                String input = responseStatusDataResult.getResult().getData().toString().replace("[", "").replace("]", "").replace("{", "").replace("}", "");
                rtmpUrl = input;

                mBinding.webViewEasyPlayer.loadUrl(easyPlayer);
                mBinding.webViewEasyPlayer.getWebView().setBackgroundColor(0); // 设置背景色
                if (!StringUtil.isEmpty(rtmpUrl)) {
                    mBinding.webViewEasyPlayer.loadUrl(easyPlayer + rtmpUrl);
                    mBinding.webViewEasyPlayer.getWebView().setBackgroundColor(0); // 设置背景色
                } else {
                    ToastUtils.showLongToast("暂无相关监控数据");

                }
            } else {
                ToastUtils.showLongToast("暂无相关监控数据");
            }

        });

    }

    private void callJavaScriptZoomToPointFunction(JsonObject object) {
        JsonArray array = new JsonArray();
        array.add(object);
        mBinding.webView.getWebView().evaluateJavascript("zoomToPointProject(" + object + "," + "'" + array + "'" + ");", null);
    }

    @Override
    public int getRequestedOrientation() {
        return super.getRequestedOrientation();
    }

    @Override
    public void onBackPressed() {
        int orientation = getRequestedOrientation();
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            // Activity 设置为横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            isLandscape = !isLandscape;
        } else
            super.onBackPressed();

    }

    @Override
    protected void onClickSecurity(View v) {
        super.onClickSecurity(v);
        if (v.getId() == R.id.title_bar_back) {
            int orientation = getRequestedOrientation();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                // Activity 设置为横屏
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                isLandscape = !isLandscape;
            } else
                finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        mBinding.webViewEasyPlayer.getWebView().evaluateJavascript("javascript:onStop();", null);
    }
}
